<template>
  <a-modal
    :maskClosable="maskClosable"
    title="编辑IT设备"
    :width="600"
    :visible="visible"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" :labelCol="labelCol" :wrapperCol="wrapperCol">
        <a-form-item label="设备类型">
          <span class="ant-form-text">{{this.model.typeCnName}}</span>
        </a-form-item>
        <a-form-item label="数据中心">
          <span class="ant-form-text">{{this.model.datacenterName}}</span>
        </a-form-item>
        <a-form-item label="机柜">
          <span class="ant-form-text"> {{ cabinetName }} </span>
        </a-form-item>
        <a-form-item label="设备名称">
          <a-input autocomplete="off" v-decorator="['name',{
            initialValue:this.model.name,
            rules:[
              {required:true,message:'设备名称不能为空',},
              { validator: validators.noWhitespace(), },
              { validator: validators.noIllegalString() },
              {max:10,message:'长度在 1 到 10 个字符', trigger: 'blur'},
              ]}]"/>
        </a-form-item>
        <a-form-item label="设备识别号">
          <a-input autocomplete="off" v-decorator="['esn',{
            initialValue:this.model.esn,
            rules:[
              {required:true,message:'设备识别号不能为空',},
              { validator: validators.noWhitespace(), },
              { validator: validators.noIllegalString() },
              {max:10,message:'长度在 1 到 10 个字符', trigger: 'blur'},
              ]}]"/>
        </a-form-item>
        <a-form-item label="设备型号">
          <a-input autocomplete="off" v-decorator="['deviceModel',{
            initialValue:this.model.deviceModel,
            rules:[
              {required:true,message:'设备型号不能为空',},
              { validator: validators.noWhitespace(), },
              { validator: validators.noIllegalString() },
              {max:10,message:'长度在 1 到 10 个字符', trigger: 'blur'},
              ]}]"/>
        </a-form-item>
        <a-form-item label="设备厂商">
          <a-input autocomplete="off" v-decorator="['deviceManufacturer',{
            initialValue:this.model.deviceManufacturer,
            rules:[
              {required:true,message:'设备厂商不能为空',},
              { validator: validators.noWhitespace(), },
              { validator: validators.noIllegalString() },
              {max:10,message:'长度在 1 到 10 个字符', trigger: 'blur'},
              ]}]"/>
        </a-form-item>
        <div v-if="type==='node'">
          <a-form-item label="管理网IP">
            <a-input autocomplete="off" v-decorator="['node.mgmIp',{
              initialValue:this.model.mgmIp,
              rules:[
                {required:true,message:'管理网IP不能为空',},
                { validator: this.validators.noWhitespace(), },
                { validator: this.validators.isValidIp(), },
                ]}]"/>
          </a-form-item>
          <a-form-item label="带外管理IP">
            <a-input autocomplete="off" v-decorator="['node.ipmiIp',{
              initialValue:this.model.ipmiIp,
              rules:[
                {required:true,message:'带外管理IP不能为空',},
                { validator: this.validators.noWhitespace(), },
                { validator: this.validators.isValidIp(), },
                ]}]"/>
          </a-form-item>
          <a-form-item label="带外管理用户">
            <a-input autocomplete="off" v-decorator="['node.ipmiUser',{
              initialValue:this.model.ipmiUser,
              rules:[
                {required:true,message:'带外管理用户不能为空',},
                { validator: validators.noWhitespace(), },
                { validator: validators.noIllegalString() },
                {max:10,message:'长度在 1 到 10 个字符', trigger: 'blur'},
                ]}]"/>
          </a-form-item>
          <a-form-item v-if="visible" label="带外管理密码">
            <a-input-password autocomplete="new-password" v-decorator="['node.ipmiPassword',{
              initialValue:this.model.ipmiPassword,
              rules:[
                {required:true,message:'带外管理密码不能为空',},
                { validator: validators.noWhitespace(), },
                { validator: validators.enName(), },
                { validator: validators.noIllegalString(), },
                {min:6,message:'带外管理密码长度不能小于6'},
                {max:20,message:'带外管理密码长度不能大于20'},
                ]}]"/>
          </a-form-item>
          <a-form-item label="主机名">
            <a-input autocomplete="off" v-decorator="['node.hostname',{
              initialValue:this.model.hostname,
              rules:[
                {required:true,message:'主机名不能为空',},
                { validator: validators.noWhitespace(), },
                { validator: validators.noIllegalString() },
                {max:10,message:'长度在 1 到 10 个字符', trigger: 'blur'},
                ]}]"/>
          </a-form-item>
          <a-form-item label="额定电压">
            <a-input autocomplete="off" :max-length="7" addon-after="V" @keyup="clearNoNum('node.ratedVoltageSm')" @blur="clearNoNum('node.ratedVoltageSm')" v-decorator="['node.ratedVoltageSm',{
              initialValue:(this.model.ratedVoltageSm ? parseFloat(this.model.ratedVoltageSm).toFixed(2) : ''),
              rules:[
                {required:true,message:'额定电压不能为空',},
                { validator: validators.xmax({max:9999}), trigger: 'blur', },
                { validator: validators.xmin({min:0}), trigger: 'blur', },
                ]}]"/>
          </a-form-item>
          <a-form-item label="额定功率">
            <a-input autocomplete="off" :max-length="7" addon-after="W" @keyup="clearNoNum('node.ratedPowerSm')" @blur="clearNoNum('node.ratedPowerSm')" v-decorator="['node.ratedPowerSm',{
              initialValue:(this.model.ratedPowerSm ? parseFloat(this.model.ratedPowerSm).toFixed(2) : ''),
              rules:[
                {required:true,message:'额定功率不能为空',},
                { validator: validators.xmax({max:9999}), trigger: 'blur', },
                { validator: validators.xmin({min:0}), trigger: 'blur', },
                ]}]"/>
          </a-form-item>
        </div>
        <div v-if="type==='switcher'">
          <a-form-item label="交换机IP">
            <a-input autocomplete="off" v-decorator="['switcher.ip',{
              initialValue:this.model.ip,
              rules:[
                {required:true,message:'交换机IP不能为空',},
                { validator: this.validators.noWhitespace(), },
                { validator: this.validators.isValidIp(), },
                ]}]"/>
          </a-form-item>
          <a-form-item label="交换机Community">
            <a-input autocomplete="off" v-decorator="['switcher.community',{
              initialValue:this.model.community,
              rules:[
                {required:true,message:'交换机Community不能为空',},
                { validator: validators.noWhitespace(), },
                { validator: validators.noIllegalString() },
                {max:10,message:'长度在 1 到 10 个字符', trigger: 'blur'},
                ]}]"/>
          </a-form-item>
        </div>
      </a-form>
    </a-spin>
  </a-modal>
</template>
<script>
import { gPostAction } from '@/api/manage'
import { sm4Encrypt, sm4Decrypt, randomString } from "@/utils/sm4"
import { sm3Hash } from "@/utils/sm3";
import { SM4_KEY } from "@/store/mutation-types";
import { filterToFloat } from "@/utils/util";

export default {
  name: 'EditModal',
  data() {
    return {
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      model: {},
      typeData:[
        {
          id:'node',
          name:'服务器'
        },
        {
          id:'switcher',
          name: '交换机'
        }
      ],
      type: 'node',
      cabinetName: undefined,
      datacenterList: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      url: {
        updateNode: '/asset/updateNode',
        updateSwitcher:'/asset/updateSwitcher',
        detailNode:'/asset/detailNode',
        detailSwitcher:'/asset/detailSwitcher',
        datacenterPage: '/asset/pageDatacenter',
      },
      id: '',
      maskClosable: false,
    }
  },
  methods: {
    clearNoNum(fieldName) {
      let obj = {}
      obj[fieldName] = filterToFloat(this.form.getFieldValue(fieldName))
      this.form.setFieldsValue(obj);
      this.form.validateFields([fieldName], (errors, values) => {});
    },
    loadDeviceDetail(cabinetId) {
      const requestData = {
        id: cabinetId,
        content: '基础设施详情'
      };
      gPostAction('/asset/detailDevice', requestData).then((res) => {
        if (res.data && res.data.name) {
          this.cabinetName = res.data.name
        } else {
          this.cabinetName = undefined
        }
      });
    },
    loadDatacenterList() {
      gPostAction(this.url.datacenterPage, {}).then((res) => {
        this.datacenterList = res.data.list
        // if (this.datacenterList.length) {
        //   this.node.datacenterId = this.datacenterList[0].id
        //   this.switcher.datacenterId =this.datacenterList[0].id
        // }
      })
    },
    edit(record) {
      this.visible = true
      this.cabinetName = undefined
      this.$nextTick(() => {
        this.form.resetFields()
        // this.loadDatacenterList()
        const data ={
          id:record.id,
          title: "精确管控与供电制冷联动-基础资源细粒度感知-资源管理-L2层：IT设备"
        }
        this.$ls.set(SM4_KEY, randomString());
        this.id = record.id
        if (record.type===6){
          gPostAction(this.url.detailNode, data).then((res) => {
            this.model = Object.assign({}, res.data);
            if (this.model.cabinetId) {
              this.loadDeviceDetail(this.model.cabinetId);
            }
            // this.loadCabinetList(this.model.datacenterId);
            if (this.model.smData) {
              let str = sm4Decrypt(this.model.smData);
              let len = str.length;
              let valStr = str.substring(0, len - 64);
              let sm3Str = str.substring(len - 64, len);
              let arr = valStr.split("|");
              if (arr && arr.length > 2) {
                this.model.ipmiPassword = arr[0];
                this.model.ratedPowerSm = arr[1];
                this.model.ratedVoltageSm = arr[2];
                if (
                  sm3Str &&
                  sm3Hash(arr[0] + '|' + arr[1] + '|' + arr[2]) !== sm3Str
                ) {
                  // this.$message.warning('数据完整性被破坏,请注意数据安全。')
                }
              }
            } else {
              // this.$message.warning('完整性被破坏,请注意数据安全。')
            }
          })
          this.type='node'
        }
        else if (record.type===7){
          gPostAction(this.url.detailSwitcher, data).then((res) => {
            this.model = Object.assign({}, res.data)
            if (this.model.community) {
              let str = sm4Decrypt(this.model.community);
              let len = str.length;
              this.model.community = str.substring(0, len - 64);
              let sm3Str = str.substring(len - 64, len);
              if (
                this.model.community &&
                sm3Str &&
                sm3Hash(this.model.community) !== sm3Str
              ) {
                // this.$message.warning('数据完整性被破坏,请注意数据安全。')
              }
            } else {
              // this.$message.warning('完整性被破坏,请注意数据安全。')
            }
          })
          this.type='switcher'
        }
      })
    },
    handleOk(e) {
      this.form.validateFields((err,values)=>{
        if (!err) {
          this.confirmLoading = true
          this.$ls.set(SM4_KEY, randomString());
          if (this.type==='node'){
            this.nodeOk(values)
          }
          else if (this.type==='switcher'){
            this.switcherOk(values)
          }
        }
      })
    },
    nodeOk(values){
      let ipmiPassword = values.node.ipmiPassword;
      let ratedVoltageSm = parseFloat(values.node.ratedVoltageSm) + '';
      let ratedPowerSm = parseFloat(values.node.ratedPowerSm) + '';
      const postData = {
        datacenterId: this.model.datacenterId,
        name:values.name,
        deviceManufacturer:values.deviceManufacturer,
        deviceModel:values.deviceModel,
        esn:values.esn,
        ipmiIp:values.node.ipmiIp,
        // ipmiPassword: sm4Encrypt(ipmiPassword + sm3Hash(ipmiPassword)),
        ipmiUser: values.node.ipmiUser,
        mgmIp: values.node.mgmIp,
        id:this.id,
        energyEfficiencyRatio: values.node.energyEfficiencyRatio,
        powerEfficiency:values.node.powerEfficiency,
        storageCapacity: values.node.storageCapacity,
        hostname:values.node.hostname,
        title: "精确管控与供电制冷联动-基础资源细粒度感知-资源管理-L2层：IT设备"
        // ratedVoltageSm: sm4Encrypt(ratedVoltageSm + sm3Hash(ratedVoltageSm)),
        // ratedPowerSm: sm4Encrypt(ratedPowerSm + sm3Hash(ratedPowerSm)),
      }

      let valStr = ipmiPassword + '|' + ratedPowerSm + '|' + ratedVoltageSm;
      let sm3Str = sm3Hash(valStr);
      postData.smData = sm4Encrypt(valStr + sm3Str);

      gPostAction(this.url.updateNode, postData)
        .then((res) => {
          if (res.success) {
            this.$message.success('操作成功')
            this.$emit('ok')
          }
        })
        .finally(() => {
          this.confirmLoading = false
          this.handleCancel()
        })
    },
    switcherOk(values){
      let str = values.switcher.community;
      const postData = {
        datacenterId: this.model.datacenterId,
        name: values.name,
        community:sm4Encrypt(str + sm3Hash(str)),
        deviceManufacturer:values.deviceManufacturer,
        deviceModel:values.deviceModel,
        esn:values.esn,
        ip:values.switcher.ip,
        id:this.id,
        title: "精确管控与供电制冷联动-基础资源细粒度感知-资源管理-L2层：IT设备"
      }

      gPostAction(this.url.updateSwitcher, postData)
        .then((res) => {
          if (res.success) {
            this.$message.success('操作成功')
            this.$emit('ok')
          }
        })
        .finally(() => {
          this.confirmLoading = false
          this.handleCancel()
        })
    },
    handleCancel(e) {
      this.visible = false
    },
  },
}
</script>
